#include "KKComm.h"
#include <string>
#include <vector>
// std::wstring text_utf8_to_utf16(const std::string &utf8) {
//     // setlocale(LC_CTYPE, locale); // zh_CN.utf8
//     mbstate_t state{};
//     int len = utf8.size();
//     wchar_t *p = new wchar_t[len+ 1];
//     char* src = (char*)utf8.data();
//     int err = mbsrtowcs_s(nullptr, p, len, (const char**)&src, len, &state);
//     if (err != 0) {
//         delete[] p;
//         return std::wstring();
//     }
//     auto retVal = std::wstring(p);
//     delete[] p;
//     return retVal;
// }

// std::string text_utf16_to_utf8(const std::wstring &utf16) {
//     // setlocale(LC_CTYPE, locale); // zh_CN.utf8
//     mbstate_t state{};
//     int len = utf16.size();
//     char *p = new char[len*3 + 1];
//     wchar_t* src = (wchar_t*)utf16.data();
//     int err = wcsrtombs_s(nullptr, p, len*3, (const wchar_t**)&src, len, &state);
//     if (err != 0) {
//         delete[] p;
//         return std::string();
//     }
//     auto retVal = std::string(p);
//     delete[] p;
//     return retVal;
// }

std::wstring text_utf8_to_utf16(const std::string &utf8)
{
    // Calculate the required buffer size for the wide character string
    int wide_len = MultiByteToWideChar(CP_UTF8, 0, utf8.data(), -1, nullptr, 0);
    // Allocate a buffer for the wide character string
    std::vector<wchar_t> buffer(wide_len);
    // Perform the conversion
    MultiByteToWideChar(CP_UTF8, 0, utf8.data(), -1, buffer.data(), wide_len);
    // Create a std::wstring from the buffer
    return std::wstring(buffer.data());
}

std::string text_utf16_to_utf8(const std::wstring &utf16)
{
    // Calculate the required buffer size for the UTF-8 string
    int utf8_len = WideCharToMultiByte(CP_UTF8, 0, utf16.data(), -1, nullptr, 0, nullptr, nullptr);
    // Allocate a buffer for the UTF-8 string
    std::vector<char> buffer(utf8_len);
    // Perform the conversion
    WideCharToMultiByte(CP_UTF8, 0, utf16.data(), -1, buffer.data(), utf8_len, nullptr, nullptr);
    // Create a std::string from the buffer (excluding the null terminator)
    return std::string(buffer.data(), buffer.size() - 1);
}